<template>
  <div>
    <el-upload
      ref="upload"
      v-bind="config"
      class="upload-view"
      :before-remove="beforeRemove"
      :on-success="onSuccess"
      :accept="accept"
      :action="action"
      :headers="headers"
      :on-remove="onRemove"
      :drag="type == 'text' ? true : false"
      :on-preview="onPreview"
      :before-upload="beforeUpload"
      :on-error="onError">
      <template v-if="type == 'text'">
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
      </template>
      <template v-if="type == 'button'">
        <slot>
          <el-button
            slot="trigger"
            size="small"
            type="primary">
            选取文件
          </el-button>
          <el-tooltip
            v-if="config && config.tipWord"
            class="item"
            effect="dark"
            :content="config.tipWord"
            placement="right">
            <i class="el-icon-info"></i>
          </el-tooltip>
        </slot>
      </template>
      <div
        slot="tip"
        class="el-upload__tip">
        <span
          v-if="format.length">只能上传{{ format.join('/') }}文件类型
          <template v-if="size">
            且不超过{{ size }}kb
          </template>
        </span>
        <span v-if="!format.length && size">文件大小不超过{{ size }}kb</span>
      </div>
    </el-upload>
    <!-- 浏览文件 -->
    <template v-if="previewView">
      <preview-file
        :file="file"
        @closePreview="closePreview" />
    </template>
  </div>
</template>
<script>
  import {
    getToken,
    getTokenType
  } from '@/utils/auth'
  import SnowflakeId from 'snowflake-id'
  export default {
    name: 'UploadFile',
    props: {
      maxSize: {
        type: [Number, String],
        default: () => 0
      },
      format: {
        type: Array,
        default: () => []
      },
      type: {
        type: String,
        default: () => 'button'
      },
      config: {
        type: Object,
        default: () => ({
          autoUpload: true
        })
      },
      fileUploadComplete: {
        type: Function,
        default: null
      },
      isImportFile: {
        type: Boolean,
        default: false
      },
      action: {
        type: String,
        default: `${process.env.VUE_APP_ADMIN_API}/enclosure/upload`
      }
      // 显示文件已上传列表
      // showFileList: {
      //   type: Array,
      //   default: () => []
      // }
    },
    data() {
      return {
        // action: `${process.env.VUE_APP_ADMIN_API}/enclosure/upload`,
        headers: {
          Authorization: getToken() ? getTokenType() + ' ' + getToken() : 'uuid',
          traceId: new SnowflakeId({
            mid: 42,
            offset: (2019 - 1970) * 31536000 * 1000
          }).generate(),
          invokeTime: +new Date(),
          'tenant-account': localStorage.tenant_accounts ? JSON.parse(localStorage.tenant_accounts).tenantId + ':' + JSON.parse(localStorage.tenant_accounts).accountId : undefined
        },
        file: {},
        previewView: false,
        uploaedFile: null
      }
    },
    computed: {
      size() {
        return this.maxSize ? (Number(this.maxSize) * 1024) : null
      },
      accept() {
        return this.format.join(',')
      }
    },
    methods: {
      beforeRemove(file, fileList) {
        if (file.status === 'success') {
          return new Promise((resolve, reject) => {
            this.$confirm(`此操作将删除文件“${file.name}”, 是否继续?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(() => {
                resolve(true)
              })
              .catch(() => {
                reject(false)
              })
          })
        }
      },
      beforeUpload(file) {
        if (this.config.typeList && !this.config.typeList.includes(file.type)) { // typeList 定制文件传输类型 typeListError定制文件传输格式错误提示信息
          this.$message.error(this.config.typeListError || '文件格式不符合要求。')
          return false
        }
        if (file.name.indexOf(' ') > -1) {
          this.$message.error('文件名不能包含空格。')
          return false
        }
        let findtime = 0
        this.$refs.upload.uploadFiles.forEach(element => {
          if (file.name === element.name) {
            findtime++
          }
        })
        if (findtime >= 2) {
          this.$message.error(`不支持上传同名文件`)
          return false
        }
        let findone = null
        const mapFiles = this.uploaedFile ? this.uploaedFile : this.config.fileList
        if (mapFiles) {
          findone = mapFiles.some(i => {
            if (i.name === file.name) {
              return true
            }
          })
        }
        if (findone) {
          this.$message.error(`不支持上传同名文件`)
          return false
        }
        if (this.size && (file.size > this.size * 1024)) {
          this.$message.error(`文件大小超过${this.size}kb`)
          return false
        }
        const suffix = file.name.substr(file.name.lastIndexOf('.') + 1)
        if (this.format.length && !this.format.includes(suffix)) {
          this.$message.error(`请选择正确的文件类型`)
          return false
        }
      },
      onSuccess(response, file, fileList) {
        // 如果是导入文件上传  调用上传成功
        if (this.isImportFile) {
          this.fileUploadComplete('success')
          return
        }
        this.filtersFileList(fileList)
      },
      filtersFileList(fileList) {
        if (this.fileUploadComplete && this.fileUploadComplete instanceof Function) {
          const list = fileList.map(item => {
            if (item.response) {
              return item.response.data
            }
            return item
          })
          // 通知 制作表单页面 附件上传完成
          this.fileUploadComplete(list)
          // 通知 上级页面 附件上传完成
          this.$emit('uploadCompleteToParent', fileList)
          // 保存上传完成的的文件
          this.uploaedFile = list
        }
      },
      onRemove(response, fileList) {
        this.filtersFileList(fileList)
      },
      onError(err) {
        if (err.message.indexOf('storage_file_size_empty') > -1) {
          this.$message.error('文件上传失败，不支持上传空文件')
        } else {
          this.$message.error(err.message ? err.message : `文件上传出错，请联系开发人员`)
        }
      },
      onPreview(file) {
        // 手动上传文件 不允许查看
        if (this.isImportFile) {
          return
        }
        if (file.response) {
          this.file.url = file.response.data.fileSavePath
        } else {
          this.file = {
            ...file,
            url: file.fileSavePath
          }
        }
        this.previewView = true
      },
      closePreview() {
        this.previewView = false
      },
      submit() {
        this.$refs.upload.submit()
      },
      clearFiles() {
        this.$refs.upload.clearFiles()
      }
    }
  }
</script>
